package cn.czu.wyw.intercept;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.sql.Connection;
import java.util.Properties;

/**
 * @Author wyw
 * @Description
 * @Date 2021/3/15 13:37
 * @Version 1.0
 */
@Slf4j
@Intercepts({
        @Signature(
                    type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class
        }),
        @Signature(type = Executor.class, method = "query",
                args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class MyPageHelp implements Interceptor {
    //把被拦截对象生成一个代理对象

    @Override
    public Object plugin(Object target) {
        log.info(target.toString());
        return Plugin.wrap(target, this);

    }

    @Override
    public void setProperties(Properties properties) {
       log.info("自定义属性:{}" , JSONObject.toJSONString(properties));
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        BoundSql boundSql = statementHandler.getBoundSql();
        String sql = boundSql.getSql();
        log.info("成功拦截了Executor的query方法,sql为{}在这里我可以做点什么",sql);
        // 改变sql语句
//        BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), oldsql + " where id=1",
//                boundSql.getParameterMappings(), boundSql.getParameterObject());
//        MappedStatement newMs = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql));
//        invocation.getArgs()[0] = newMs;
        return invocation.proceed();
    }
}
